<template>
  <div class="home">
    <img
      src="../../assets/images/bg.png"
      style="position: absolute;width: 100%;z-index: 1;top:0;left:0;">
    <div
      style="overflow: hidden;width: 100vw;height: 100vh;position: fixed;z-index: 2;top: 0;left: 0;display: flex;justify-content: center; align-items: center;">
      <div class="chat_box">
        <div
          class="chat_left">

          <template
            v-if="chatLastList.length > 0">
            <!-- {{ chatLastList }} -->
            <div
              class="chat_item"
              @click="ChangeChat(index)"
              v-for="(item,index) in chatLastList"
              :key="index">
              <div class="tx">
                <img
                  src="../../assets/images/left.png"
                  style="width:40px;height: 40px;border-radius: 40px;"
                  alt="">
              </div>
              <div
                class="text_box">
                <div
                  v-if="JSON.parse(item.useValue[0].content).type == 'message'">
                  {{JSON.parse(item.useValue[0].content).text }}

                </div>
                <div v-else>
                  {{JSON.parse(item.useValue[0].content).fileName}}
                </div>
              </div>
              <div
                class="close_item"
                @click="delItem(item,index)">
                x</div>
            </div>
          </template>
          <template v-else>
            <div
              class="chat_item"
              v-for="item in list"
              :key="item">
              <div class="tx">
              </div>
              <div
                class="line">
              </div>
            </div>
          </template>
        </div>
        <div
          class="chat_right">
          <div
            class="chat_right_top">
            <div class="left">
            </div>
            <div
              class="center">
              <img
                src="../../assets/images/right.png"
                style="width: 50px; height: 50px;border-radius: 50px;" />
            </div>
            <div
              class="rights_round"
              @click="goback()">
              <div
                class="round">
                x
              </div>
            </div>
          </div>
          <div
            class="chat_right_body"
            id="containerRef">
            <template
              v-for="(item,index) in chatList"
              :key="index">
              <div
                class="chat_items user  animate__animated animate__fadeInRight"
                v-if="item.role == 'user'">
                <div
                  class="chat_content_box">
                  <div
                    v-if="JSON.parse(item.content).type =='message'">
                    {{JSON.parse(item.content).text}}
                  </div>
                  <div
                    style="display: flex;flex-flow: column;align-items: center;justify-content: center;"
                    v-if="JSON.parse(item.content).type =='img'">
                    <img
                      :src="JSON.parse(item.content).imgUrl"
                      style="width:100%;" />
                    <div>
                      <div
                        v-if="JSON.parse(item.content).text">
                        {{JSON.parse(item.content).text}}
                      </div>
                    </div>
                  </div>
                  <div
                    v-if="JSON.parse(item.content).type =='file'">
                    <a :href="JSON.parse(item.content).fileUrl"
                      style="text-decoration: none;">
                      <text
                        style="color:blanchedalmond">

                        {{JSON.parse(item.content).fileName}}</text>
                    </a>
                  </div>
                </div>
                <div
                  class="chat_content_tx user ">
                  <img
                    src="../../assets/images/left.png"
                    alt=""
                    style="width:100%;height:100%;border-radius: 80px;">
                </div>
              </div>
              <div
                class="chat_items ai animate__animated animate__fadeInLeft"
                v-if="item.role == 'assistant'">
                <div
                  class="chat_content_tx ai">
                  <img
                    src="../../assets/images/logo.png"
                    alt=""
                    style="width:100%;height:100%;border-radius: 80px;">
                </div>
                <div
                  class="chat_content_box">

                  <span>
                    <Marked
                      :content="item.contents">
                    </Marked>
                  </span>
                </div>
              </div>
            </template>
          </div>
          <div
            class="chat_right_footer">

            <div
              class="input_box">
              <el-upload
                :disabled="disabled"
                class="upload-demo"
                style="width:100px;height:100px;display: flex;justify-content: center;align-items: center;"
                :headers="{
                'token': store.state.token,
              }
              " name="file"
                :action="HTTP_URL.BASEURL+'/base/upload'"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false">
                <img
                  v-if="fileObj.url"
                  :src="fileObj.url"
                  style="width: 60px;max-height: 58px; margin: 0 "
                  alt="">
                <img v-else
                  src="@/assets/images/upload.png"
                  style="width: 60px; max-height: 58px; margin: 0 " />
              </el-upload>
              <input
                type="text"
                style="line-height: 18px;height: 60px;padding:10px 0; font-size: 18px; padding:0 10px;"
                :disabled="disabled"
                placeholder="Please enter"
                v-model="sendText"
                @keydown.enter="sendFun" />
              <div
                class="send"
                @click="sendFun">
                Send</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      style="width: 100%;height: 200px;position: fixed;top: -9999px;">
      <Scoket
        @onMessage="onMessage">
      </Scoket>
    </div>
    <MarkedBox
      v-if="showTishi"
      @ok="ok"
      @cancel='cancel'>
    </MarkedBox>
  </div>
</template>
<script setup lang="ts">
import { HTTP_URL } from '@/api/api'
import axios from 'axios'
import Scoket from '@/components/scoket/index.vue'
import { ref, onMounted, reactive, computed, watch } from 'vue'
import store from '@/store'
import Marked from '@/components/marked/index.vue'
import MarkedBox from '@/components/markbox/index.vue'
import { ElMessage, UploadProps, ElLoading, formatter, ElMessageBox } from 'element-plus'
import router from '@/router'
const list = ref([1, 2, 3, 4, 5, 6, 7, 8])
const chatList = ref([])
const chatLists = ref('')
const sendText = ref('')
const fileObj = ref({})
let messages = ref('')
const showTishi = ref(false)
const chatLastList = ref([])
const loading = ref(false)
const disabled = ref(false)
const delObj = ref({})
onMounted(() => {
  getData()

  const days = window.localStorage.getItem('day')
  if (days && days == getYearDay()) {
    console.log('今日登录')
  } else {
    window.localStorage.removeItem('logId')
    store.commit('setLogId', '')
  }
  const token = store.state.token
  if (!token) {
    axios({
      url: HTTP_URL.BASEURL + '/auth/user/login',
      method: 'post',
      data: {
        browserFingerprint: new Date().getTime()
      }
    }).then((res: any) => {
      store.commit('setToken', res.data.data.token)
      store.commit('setUserId', res.data.data.userId)
      store.commit('setUserType', res.data.data.userType)
      store.commit('setUserName', res.data.data.name)
      window.localStorage.setItem('day', getYearDay())

      window.localStorage.setItem('userId', res.data.data.userId)
      window.localStorage.setItem('token', res.data.data.token)
      window.localStorage.setItem('userType', res.data.data.userType)
      window.localStorage.setItem('name', res.data.data.name)
    })
  }
})
const message = computed(() => {
  return store.state.message
})
watch(
  message,
  newVal => {
    console.log(newVal)
    messages.value = newVal

    setTimeout(() => {
      scrollToBottom()
    }, 100)
  },
  { immediate: true, deep: true }
)
const getYearDay = () => {
  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() < 10 ? `0` + `${date.getMonth() + 1}` : date.getMonth() + 1
  var day = date.getDate() < 10 ? `0` + `${date.getDate()}` : date.getDate()
  return year + '-' + month + '-' + day
}
const goback = () => {
  router.push('/')
}
const ChangeChat = (index: any) => {
  chatList.value = chatLastList.value[index].useValue
  setTimeout(() => {
    scrollToBottom()
  }, 1000)
}
const delItem = (item: any, index: number) => {
  showTishi.value = true
  delObj.value = item
}
const ok = (data: any) => {
  axios({
    url: HTTP_URL.BASEURL + '/base/delete/log',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Token: store.state.token
    },
    data: {
      logId: delObj.value.id
    }
  }).then(res => {
    getData()
    showTishi.value = false
    delObj.value = {}
  })
}
const cancel = () => {
  getData()
  showTishi.value = false
  delObj.value = {}
}
const getData = () => {
  sendText.value = ''
  axios({
    url: HTTP_URL.BASEURL + '/base/home',
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Token: store.state.token
    },
    data: {
      advertisementType: 2
    }
  }).then((res: any) => {
    if (res.data.status == 200) {
      if (res.data.data.messageLogList && res.data.data.messageLogList.length > 0) {
        console.log(res.data.data.messageLogList, 'oooooo')
        chatLastList.value = res.data.data.messageLogList
        chatLastList.value.forEach(item => {
          item.useValue = JSON.parse(item.useValue)
        })
        // 判断 createTime 截取年月日
        chatList.value = chatLastList.value[0].useValue
        console.log(chatList.value, 'chatList.value')
        chatList.value.forEach(item => {
          item.contents = JSON.parse(item.content).answer
        })
        window.localStorage.setItem('logId', chatLastList.value[0].id)
        setTimeout(() => {
          scrollToBottom()
          const num: Number = chatList.value.length - 1
          if (num) {
            const content = JSON.parse(chatList.value[num].content)
            console.log(content, '00000')
            window.localStorage.setItem('conversationId', content.conversationId)
          }
        }, 500)
      } else {
        window.localStorage.setItem('logId', '')
        chatLastList.value = []
        chatList.value = []
      }
    }
  })
}
const sendFun = () => {
  if (sendText.value == '') {
    return
  }

  let obj: any = {}
  disabled.value = true
  const logId = window.localStorage.getItem('logId')

  if (fileObj.value && fileObj.value.url) {
    obj = {
      role: 'user',
      content: JSON.stringify({
        imgUrl: fileObj.value.url,
        text: sendText.value,
        type: 'img'
      })
    }
  } else {
    obj = {
      role: 'user',
      content: JSON.stringify({
        text: sendText.value,
        type: 'message'
      })
    }
  }

  const objs: any = {
    role: 'assistant',
    content: JSON.stringify({
      answer: '...'
    }),
    contents: '...'
  }

  if (chatLastList.value.length > 0) {
    if (chatLastList.value[0].createTime.substring(0, 10) == getYearDay()) {
      chatList.value.push(obj, objs)
    } else {
      const objss: any = {
        createTime: getYearDay() + 'T00:00:00',
        useValue: [obj, objs]
      }

      chatLastList.value.push(objss)
      chatList.value = chatLastList.value[0].useValue
      console.log(chatList.value, 'fileObj.value.url')
    }
  } else {
    console.log(obj, 'obj')
    const objss: any = {
      createTime: getYearDay() + 'T00:00:00',
      useValue: [obj, objs]
    }
    chatLastList.value.push(objss)
    chatList.value = chatLastList.value[0].useValue
    console.log(chatList.value, 'fileObj.value.url')
  }

  store.commit('setMessageList', chatList.value)

  if (fileObj.value.url) {
    const objesss: any = {
      problem: sendText.value,
      url: fileObj.value.url,
      logId: logId
    }
    axios({
      url: HTTP_URL.BASEURL + '/ai/gpt/chat',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
        Token: store.state.token
      },
      data: objesss
    }).then((res: any) => {
      if (chatLastList.value[0].createTime.substring(0, 10) == getYearDay()) {
        console.log(res)
        store.commit('setLogId', res.data.data.logId)
        fileObj.value = ''
        window.localStorage.setItem('logId', res.data.data.logId)
      } else {
        store.commit('setLogId', res.data.data.logId)
        window.localStorage.setItem('logId', res.data.data.logId)
      }
    })
  } else {
    let conversationId = window.localStorage.getItem('conversationId')
    const objess: any = {
      query: sendText.value,
      url: fileObj.value.url ? fileObj.value.url : '',
      logId: logId,
      conversationId: conversationId !== 'undefined' || !conversationId ? conversationId : ''
    }
    axios({
      url: HTTP_URL.BASEURL + '/ai/dify/chat',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
        Token: store.state.token
      },
      data: objess
    }).then((res: any) => {
      if (chatLastList.value[0].createTime.substring(0, 10) == getYearDay()) {
        console.log(res)
        store.commit('setLogId', res.data.data.logId)
        fileObj.value = ''
        window.localStorage.setItem('logId', res.data.data.logId)
      } else {
        store.commit('setLogId', res.data.data.logId)
        window.localStorage.setItem('logId', res.data.data.logId)
      }
    })
  }

  setTimeout(() => {
    sendText.value = ''
    scrollToBottom()
  }, 500)
  // getData()
}
/*
 * 滚动到底部的操作
 * */
const scrollToBottom = () => {
  let divHeight: any = document.getElementById('containerRef') // 获取整个页面的高度
  divHeight.scrollTo({
    top: divHeight?.scrollHeight, //回到底部
    left: 0,
    behavior: 'smooth' //smooth 平滑；auto:瞬间
  })
}
const content = ref('')
const onMessage = (msg: any) => {
  const data = JSON.parse(msg)
  console.log(data, 'data')
  if (data == '[DONE]') {
    console.log('结束')
    getData()
    content.value = ''
    disabled.value = false
    fileObj.value = {}
  } else {
    loading.value = false
    content.value += data
    chatList.value[chatList.value.length - 1].content = JSON.stringify({
      answer: content.value
    })
    chatList.value[chatList.value.length - 1].contents = content.value
    scrollToBottom()
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  if (uploadFile.raw?.type == 'image/jpeg' || uploadFile.raw?.type == 'image/png') {
    loading.value = true
    if (response.status == 200) {
      loading.value = true
      fileObj.value = response.data
      console.log(response.data, 'response.data')
    }
  } else {
    if (response.status == 200) {
      loading.value = true
      disabled.value = true
      sendFile(response.data)
    }
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (rawFile.size / 1024 / 1024 > 20) {
    ElMessage.error('文件大小不能超过20MB!')
    return false
  } else {
    console.log(rawFile, 'oooo')
    if (!rawFile.type.includes('image')) {
      const obj: any = {
        role: 'user',
        content: JSON.stringify({
          fileUrl: '',
          fileName: rawFile.name,
          text: '',
          type: 'file'
        })
      }
      const objs: any = {
        role: 'assistant',
        content: JSON.stringify({
          answer: '...'
        }),
        contents: '...'
      }
      chatList.value.push(obj)
      chatList.value.push(objs)
      setTimeout(() => {
        scrollToBottom()
      }, 500)
    }
  }
}
const sendFile = (url: String) => {
  const logId = window.localStorage.getItem('logId')
  const obj: any = {
    role: 'user',
    content: JSON.stringify({
      fileUrl: url.fileUrl,
      fileName: url.fileName,
      text: '',
      type: 'file'
    })
  }
  const objs: any = {
    role: 'assistant',
    content: JSON.stringify({
      answer: '...'
    }),
    contents: '...'
  }
  chatList.value.push(obj)
  chatList.value.push(objs)
  setTimeout(() => {
    scrollToBottom()
  }, 500)
  const objss: any = {
    fileUrl: url.url,
    fileName: url.fileName,
    logId: logId
  }
  axios({
    url: HTTP_URL.BASEURL + '/ai/kimi/chat',
    data: objss,
    headers: {
      'Content-Type': 'application/json',
      Token: store.state.token
    },
    method: 'post'
  }).then(res => {
    window.localStorage.setItem('logId', res.data.data.logId)
    store.commit('setLogId', res.data.data.logId)
    console.log(res)
  })
}
</script>

<style scoped lang="scss">
.home {
  width: 100vw;
  height: 100vh;
  background-position: -40px 0px;
  // background: url("../../assets/images/bg.png") 100% no-repeat;
  overflow: hidden;
  justify-content: center;
  align-items: center;
  display: flex;
  .chat_box {
    width: 90vw;
    height: 90vh;
    border: 2px solid rgba(138, 135, 115, 1);
    border-radius: 10px;
    overflow: hidden;
    max-width: 1200px;
    display: flex;
    align-items: center;
    .chat_left {
      width: 300px;
      border-right: 2px solid rgba(138, 135, 115, 1);
      height: 90vh;
      overflow-y: auto;
      .chat_item:first-child {
        margin-top: 50px;
      }
      .chat_item {
        display: flex;
        align-items: center;
        margin: 30px 0;
        cursor: pointer;
        padding: 5px 0;
        &:hover {
          background: rgba(255, 255, 255, 0.2);
          .close_item {
            display: block;
          }
        }
        .tx {
          width: 40px;
          height: 40px;
          border-radius: 40px;
          background: rgba(138, 135, 115, 1);
          margin-left: 20px;
        }
        .text_box {
          margin-left: 10px;
          width: 180px;
          color: #ffffff;
          /*1. 先强制一行内显示文本*/
          white-space: nowrap;
          /*2. 超出的部分隐藏*/
          overflow: hidden;
          /*3. 文字用省略号替代超出的部分*/
          text-overflow: ellipsis;
        }
        .close_item {
          color: #fafafa;
          display: none;
        }
        .line {
          width: 180px;
          height: 4px;
          background: rgba(138, 135, 115, 1);
          margin-left: 20px;
        }
      }
    }
    .chat_right {
      width: calc(90vw - 200px);
      max-width: 900px;
      height: 90vh;
      .chat_right_top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 60px;
        width: 100%;
        border-bottom: 2px solid rgba(138, 135, 115, 1);
        .left {
          width: 100px;
          margin-left: 30px;
        }
        .center {
          width: 50px;
        }
        .rights_round {
          width: 30px;
          display: flex;
          margin-right: 30px;
          justify-content: flex-end;
          align-items: center;
          color: #ffffff;
          .round {
            width: 25px;
            cursor: pointer;
            height: 25px;
            border-radius: 50%;
            text-align: center;
            background: rgba(138, 135, 115, 1);
          }
        }
      }
      .chat_right_body {
        width: 100%;
        height: calc(90vh - 165px);
        overflow-y: auto;
        overflow-x: hidden;
        .chat_items.user {
          justify-content: flex-end;
        }
        .chat_items.ai {
          justify-content: flex-start;
        }
        .chat_items {
          display: flex;
          align-items: center;
          padding: 30px 50px;
          .chat_content_box {
            max-width: 550px;
            background: linear-gradient(to right, rgba(40, 152, 116, 1), rgba(40, 152, 116, 0.4));
            padding: 20px;
            border-radius: 5px;
            color: #ffffff;
            box-shadow: 3px 3px 5px rgb(0, 30, 30, 0.5);
          }
          .chat_content_tx {
            width: 50px;
            height: 50px;
            border-radius: 50%;
          }
          .chat_content_tx.user {
            background: #fafafa;
            margin-left: 20px;
          }
          .chat_content_tx.ai {
            width: 50px;
            min-width: 50px;
            height: 50px;
            border-radius: 50px;
          }
          .chat_content_tx {
            width: 50px;
            height: 50px;
            border-radius: 50%;
          }
          .chat_content_tx.user {
            background: #fafafa;
            margin-left: 20px;
          }
          .chat_content_tx.ai {
            background: rgba(79, 97, 78, 1);
            margin-right: 20px;
          }
        }
      }
      .chat_right_body::-webkit-scrollbar {
        width: 8px; /* 设置滚动条的宽度 */
      }

      /* 自定义滚动条轨道 */
      .chat_right_body::-webkit-scrollbar-track {
        background: transparent; /* 设置轨道的背景颜色 */
      }

      /* 自定义滚动条的滑块（thumb） */
      .chat_right_body::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.5); /* 设置滑块的背景颜色 */
        border-radius: 10px;
      }

      /* 当滑块悬停或活动时自定义 */
      .chat_right_body::-webkit-scrollbar-thumb:hover {
        background: #444444; /* 设置滑块在悬停状态下的背景颜色 */
      }
      .chat_right_footer {
        display: flex;
        width: 100%;
        align-items: center;
        justify-content: space-between;
        height: 100px;
        .input_box {
          width: 100%;
          max-width: 820px;
          margin-left: 40px;
          margin-right: 10px;
          border: 1px solid rgba(138, 135, 115, 1);
          border-radius: 5px;
          height: 60px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          input {
            outline: none;
            border: none;
            background: transparent;
            width: 100%;
            height: 100%;
            color: #ffffff;
          }
          input:disabled {
            cursor: no-drop;
          }
          .send {
            width: 100px;
            height: 56px;
            text-align: center;
            line-height: 56px;
            color: #fff;
            background: linear-gradient(to right, rgba(9, 146, 171, 0.8), rgba(9, 146, 171, 0.4));
            border-radius: 5px;
            cursor: pointer;

            font-size: 20px;
            margin-right: 2px;
          }
        }
      }
    }
  }
}
</style>
